package com.best4cloud.auth.security.wechat.openid;

import com.best4cloud.auth.service.BestUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class OpenIdAuthenticationProvider implements AuthenticationProvider {

    private final BestUserDetailsService userDetailsService;

    public OpenIdAuthenticationProvider(BestUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
        String openId = (String) authenticationToken.getPrincipal();
        UserDetails user = userDetailsService.loadUserByUnionId(openId);
        if (user == null) {
            throw new InternalAuthenticationServiceException("账户名或密码错误！");
        }
        OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(openId, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return OpenIdAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
